﻿using System;
using System.Collections.Generic;
using System.Linq;
using GCTrackableRace.Interfaces;
using System.IO;
using GcTrackableRace.Entities;

namespace GcTrackableRace.Persistence
{
	public class ConfigurationSettings : IConfigurationSettings
	{
		public IProgramConfigurationSettings ReadProgramConfigurationFromFile(string fileNameAndLocation)
		{
			if (!File.Exists(fileNameAndLocation))
			{
				throw new FileNotFoundException(fileNameAndLocation);
			}

			var contents = File.ReadLines(fileNameAndLocation);

			var raceName = Path.GetFileName(fileNameAndLocation).Split('.')[0];

			var programConfigurationSettings = new ProgramConfigurationSettings();

			programConfigurationSettings.TrackableRaceName = raceName;

			var outputFormats = new List<string>();

			var raceRuleParameters = new List<List<Tuple<string, string>>>();

			foreach (var line in contents)
			{
				if (line.StartsWith("GeocacheDatabaseNameAndLocation"))
				{
					programConfigurationSettings.GeocacheDatabaseNameAndLocation = line.Split('=')[1].Trim(' ', '"');
				}

				if (line.StartsWith("GcTrackableRaceDatabaseNameAndLocation"))
				{
					programConfigurationSettings.GcTrackableRaceDatabaseNameAndLocation = line.Split('=')[1].Trim(' ', '"');
				}

				if (line.StartsWith("TrackablesDatabaseNameAndLocation"))
				{
					programConfigurationSettings.TrackablesDatabaseNameAndLocation = line.Split('=')[1].Trim(' ', '"');
				}

				if (line.StartsWith("OutputDirectory"))
				{
					programConfigurationSettings.OutputDirectory = line.Split('=')[1].Trim(' ', '"');
				}

				if (line.StartsWith("OutputFormat"))
				{
					outputFormats.Add(line.Split('=')[1].Trim(' ', '"'));
				}

				if (line.StartsWith("RaceRule"))
				{
					var raceRuleInfo = new List<Tuple<string, string>>();

					var items = line.Trim().Split(',');

					foreach (var item in items)
					{
						var subitem = item.Split('=');
						var name = subitem[0].Trim();
						var value = subitem[1].Trim(' ', '"');

						raceRuleInfo.Add(new Tuple<string, string>(name, value));
					}

					raceRuleParameters.Add(raceRuleInfo);
				}

			}

			programConfigurationSettings.OutputFormats = outputFormats;

			programConfigurationSettings.RaceRuleParameters = raceRuleParameters;

			return programConfigurationSettings;
		}

		public IEnumerable<string> GetAllRaceRuleFilesFromFolder(string directoryToSearch)
		{
			if (Directory.Exists(directoryToSearch))
			{
				return Directory.GetFiles(directoryToSearch).Where(file =>
					{
						var fileName = Path.GetFileName(file);

						return fileName != null && fileName.Contains(".RaceRules.");
					});
			}

			return new List<string>();
		}
	}
}
